package com.nine.common.tool;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @Description:
 * @ClassName: handleUpload
 * @Author: luodeng
 * @Date: 2023/6/17 12:21
 * @Version: 1.0
 */
@Component
public class AliyunOss {

        // 阿里云 OSS 的配置信息
        @Value("${ali.accessKey_id}")
        private String accessKey_id;

        @Value("${ali.accessKey_secret}")
        private String accessKeySecret;

        @Value("${ali.bucket}")
        private String bucketName;

        @Value("${ali.auditPath}")
        private String auditPath;

        @Value(("${ali.orderPath}"))
        private String orderPath;

        private String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    public void handleUploadAudit(File file,String fileName) {


        // 创建 OSS 客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey_id, accessKeySecret);

        try {
            // 指定在 OSS 上的保存路径和文件名
            String objectKey = auditPath+fileName;

            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectKey, file);
            // 设置文件权限为公共读
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setObjectAcl(CannedAccessControlList.PublicRead);
            putObjectRequest.setMetadata(metadata);

            // 执行上传操作
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

        } catch (Exception e) {
            // 处理上传失败的情况
            e.printStackTrace();
        } finally {
            // 关闭 OSS 客户端
            ossClient.shutdown();
        }

    }

    //TODO 上传多张照片
    public void handleUploadOrder(File file,String fileName,String filePath) {


        // 创建 OSS 客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey_id, accessKeySecret);

        try {
            // 指定在 OSS 上的保存路径和文件名
            String objectKey = orderPath+filePath+"/"+fileName;

            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectKey, file);
            // 设置文件权限为公共读
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setObjectAcl(CannedAccessControlList.PublicRead);
            putObjectRequest.setMetadata(metadata);

            // 执行上传操作
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

        } catch (Exception e) {
            // 处理上传失败的情况
            e.printStackTrace();
        } finally {
            // 关闭 OSS 客户端
            ossClient.shutdown();
        }

    }
}
